<template>
  <div class="data-board-split">
    <div class="header">
      <h1>数据图表</h1>

    </div>

    <div class="data-tabs">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="文章数据" name="articles">
          <div class="chart-container">
            <div ref="articleChart" class="chart"></div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="灾害数据" name="disasters">
          <div class="chart-container">
            <div ref="disasterChart" class="chart"></div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="文章地图分布" name="articleMap">
          <div class="chart-container">
            <div ref="articleMapChart" class="chart map-chart"></div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="灾害地图分布" name="disasterMap">
          <div class="chart-container">
            <div ref="disasterMapChart" class="chart map-chart"></div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="灾害类型" name="disasterType">
          <div class="chart-container">
            <div ref="disasterTypeChart" class="chart"></div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="用户活跃度" name="userActivity">
          <div class="chart-container">
            <div ref="userActivityChart" class="chart"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import * as echarts from 'echarts';
import chinaJson from './china.json';

// 当前选中的 tab
const activeTab = ref('articles');


// 图表引用
const articleChart = ref(null);
const disasterChart = ref(null);
const disasterTypeChart = ref(null);
const articleMapChart = ref(null);
const disasterMapChart = ref(null);
const userActivityChart = ref(null);

// 存储所有图表实例以便于统一管理
const charts = [];

// 文章数据测试数据
const articleData = {
  months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  values: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330]
};

// 灾害数据测试数据
const disasterData = {
  months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  values: [20, 32, 51, 84, 120, 230, 210, 120, 110, 80, 30, 40]
};

// 灾害类型测试数据
const disasterTypeData = [
  { value: 235, name: '地震' },
  { value: 274, name: '洪水' },
  { value: 310, name: '山体滑坡' },
  { value: 335, name: '道路塌方' },
  { value: 400, name: '内涝' }
];

// 用户活跃度测试数据
const userActivityData = {
  days: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
  values: [820, 932, 901, 934, 1290, 1330, 1320]
};

// 更新文章地图分布测试数据 - 确保省份名称与地图匹配
const articleMapData = [
  { name: '北京市', value: 235 },
  { name: '上海市', value: 274 },
  { name: '广东省', value: 310 },
  { name: '浙江省', value: 335 },
  { name: '四川省', value: 278 },
  { name: '湖北省', value: 189 },
  { name: '江苏省', value: 234 },
  { name: '陕西省', value: 167 },
  { name: '山东省', value: 145 },
  { name: '重庆市', value: 210 },
  { name: '天津市', value: 123 },
  { name: '湖南省', value: 178 },
  { name: '福建省', value: 156 },
  { name: '河南省', value: 187 },
];

// 更新灾害地图分布测试数据 - 确保省份名称与地图匹配
const disasterMapData = [
  { name: '四川', value: 125 },
  { name: '云南', value: 174 },
  { name: '广东', value: 210 },
  { name: '湖南', value: 235 },
  { name: '黑龙江', value: 178 },
  { name: '新疆', value: 89 },
  { name: '浙江', value: 134 },
  { name: '陕西', value: 67 },
  { name: '江苏', value: 45 },
  { name: '重庆', value: 110 },
  { name: '河南', value: 156 },
  { name: '河北', value: 98 },
  { name: '山东', value: 123 },
  { name: '安徽', value: 87 },
  { name: '广西', value: 145 }
];

// 监听 tab 切换，重新渲染当前图表
watch(activeTab, (newTab) => {
  setTimeout(() => {
    switch(newTab) {
      case 'articles':
        initArticleChart();
        break;
      case 'disasters':
        initDisasterChart();
        break;
      case 'articleMap':
        initArticleMapChart();
        break;
      case 'disasterMap':
        initDisasterMapChart();
        break;
      case 'disasterType':
        initDisasterTypeChart();
        break;
      case 'userActivity':
        initUserActivityChart();
        break;
    }
  }, 100); // 给DOM一点时间来更新
});

// 监听窗口大小变化，重新调整图表大小
window.addEventListener('resize', () => {
  charts.forEach(chart => {
    chart.resize();
  });
});

// 组件卸载时清理图表实例
onMounted(() => {
  // 注册中国地图
  echarts.registerMap('china', chinaJson);
  console.log('中国地图已注册'); // 调试信息

  // 初始化第一个图表
  initArticleChart();
});

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
};

// 添加文章发布量图表
const initArticleChart = () => {
  if (!articleChart.value) return;

  // 清除旧图表
  const existingChart = charts.find(chart => chart.__ecInstance && chart.__ecInstance.id === 'articleChart');
  if (existingChart) {
    existingChart.dispose();
    charts.splice(charts.indexOf(existingChart), 1);
  }

  const chart = echarts.init(articleChart.value);
  chart.__ecInstance = { id: 'articleChart' };
  charts.push(chart);

  const option = {
    title: {
      text: '文章月发布量',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: articleData.months
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: articleData.values,
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }]
  };

  chart.setOption(option);
};

// 添加灾害发布量图表
const initDisasterChart = () => {
  if (!disasterChart.value) return;

  // 清除旧图表
  const existingChart = charts.find(chart => chart.__ecInstance && chart.__ecInstance.id === 'disasterChart');
  if (existingChart) {
    existingChart.dispose();
    charts.splice(charts.indexOf(existingChart), 1);
  }

  const chart = echarts.init(disasterChart.value);
  chart.__ecInstance = { id: 'disasterChart' };
  charts.push(chart);

  const option = {
    title: {
      text: '灾害月发布量',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: disasterData.months,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [{
      name: '灾害数',
      type: 'line',
      data: disasterData.values,
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        color: '#f56c6c',
        width: 3
      },
      itemStyle: {
        color: '#f56c6c'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(245, 108, 108, 0.5)' },
          { offset: 1, color: 'rgba(245, 108, 108, 0.1)' }
        ])
      }
    }]
  };

  chart.setOption(option);
};

// 修复文章地图初始化函数 - 添加调试信息
const initArticleMapChart = () => {
  if (!articleMapChart.value) return;

  console.log('初始化文章地图', articleMapData); // 调试信息

  // 清除旧图表
  const existingChart = charts.find(chart => chart.__ecInstance && chart.__ecInstance.id === 'articleMapChart');
  if (existingChart) {
    existingChart.dispose();
    charts.splice(charts.indexOf(existingChart), 1);
  }

  const chart = echarts.init(articleMapChart.value);
  chart.__ecInstance = { id: 'articleMapChart' };
  charts.push(chart);

  const option = {
    title: {
      text: '文章地区分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return params.name + ': ' + (params.value || 0) + ' 篇';
      }
    },
    visualMap: {
      min: 0,
      max: 350,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
      inRange: {
        color: ['#e0f3f8', '#045fb4', '#0b2c5f']
      }
    },
    series: [
      {
        name: '文章数量',
        type: 'map',
        map: 'china',
        roam: true,
        emphasis: {
          label: {
            show: true
          }
        },
        data: articleMapData // 直接使用测试数据
      }
    ]
  };

  chart.setOption(option);
  console.log('文章地图已设置选项', option); // 调试信息
};

// 修复灾害地图初始化函数 - 添加调试信息
const initDisasterMapChart = () => {
  if (!disasterMapChart.value) return;

  console.log('初始化灾害地图', disasterMapData); // 调试信息

  // 清除旧图表
  const existingChart = charts.find(chart => chart.__ecInstance && chart.__ecInstance.id === 'disasterMapChart');
  if (existingChart) {
    existingChart.dispose();
    charts.splice(charts.indexOf(existingChart), 1);
  }

  const chart = echarts.init(disasterMapChart.value);
  chart.__ecInstance = { id: 'disasterMapChart' };
  charts.push(chart);

  const option = {
    title: {
      text: '灾害地区分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return params.name + ': ' + (params.value || 0) + ' 起';
      }
    },
    visualMap: {
      min: 0,
      max: 250,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
      inRange: {
        color: ['#ffedeb', '#ff7875', '#a8071a']
      }
    },
    series: [
      {
        name: '灾害数量',
        type: 'map',
        map: 'china',
        roam: true,
        emphasis: {
          label: {
            show: true
          }
        },
        data: disasterMapData // 直接使用测试数据
      }
    ]
  };

  chart.setOption(option);
  console.log('灾害地图已设置选项', option); // 调试信息
};

// 添加灾害类型图表
const initDisasterTypeChart = () => {
  if (!disasterTypeChart.value) return;

  // 清除旧图表
  const existingChart = charts.find(chart => chart.__ecInstance && chart.__ecInstance.id === 'disasterTypeChart');
  if (existingChart) {
    existingChart.dispose();
    charts.splice(charts.indexOf(existingChart), 1);
  }

  const chart = echarts.init(disasterTypeChart.value);
  chart.__ecInstance = { id: 'disasterTypeChart' };
  charts.push(chart);

  const option = {
    title: {
      text: '灾害类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['地震', '洪水', '台风', '山体滑坡', '泥石流', '火灾', '其他']
    },
    series: [
      {
        name: '灾害类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: disasterTypeData
      }
    ]
  };

  chart.setOption(option);
};

// 添加用户活跃度图表
const initUserActivityChart = () => {
  if (!userActivityChart.value) return;

  // 清除旧图表
  const existingChart = charts.find(chart => chart.__ecInstance && chart.__ecInstance.id === 'userActivityChart');
  if (existingChart) {
    existingChart.dispose();
    charts.splice(charts.indexOf(existingChart), 1);
  }

  const chart = echarts.init(userActivityChart.value);
  chart.__ecInstance = { id: 'userActivityChart' };
  charts.push(chart);

  const option = {
    title: {
      text: '用户活跃度趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: userActivityData.days,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [{
      name: '用户活跃度',
      type: 'line',
      data: userActivityData.values,
      smooth: true,
      symbol: 'emptyCircle',
      symbolSize: 8,
      itemStyle: {
        color: '#42b983'
      },
      lineStyle: {
        color: '#42b983',
        width: 3
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(66, 185, 131, 0.5)' },
          { offset: 1, color: 'rgba(66, 185, 131, 0.1)' }
        ])
      }
    }]
  };

  chart.setOption(option);
};

// 模拟获取地理坐标的函数
// 实际应用中应该有一个完整的地理坐标映射表
const getGeoCoord = (name) => {
  const geoCoordMap = {
    '北京': [116.4551, 40.2539],
    '上海': [121.4648, 31.2891],
    '广州': [113.5107, 23.2196],
    '深圳': [114.5435, 22.5439],
    '成都': [104.0668, 30.5728],
    '重庆': [107.7539, 30.1904],
    '天津': [117.4219, 39.4189],
    '杭州': [120.2052, 30.2526],
    '西安': [108.9402, 34.3416],
    '武汉': [114.3896, 30.6628],
    '南京': [118.8062, 31.9208],
    '郑州': [113.4668, 34.6234],
    '长沙': [112.9351, 28.2277],
    '福州': [119.4543, 25.9222],
    '济南': [117.1582, 36.8701],
    '广东': [113.12244, 23.009505],
    '四川': [104.065735, 30.659462],
    '江苏': [118.767413, 32.041544],
    '浙江': [120.153576, 30.287459],
    '河南': [113.665412, 34.757975],
    '河北': [114.502461, 38.045474],
    '山东': [117.000923, 36.675807],
    '湖北': [114.298572, 30.584355],
    '湖南': [112.982279, 28.19409],
    '辽宁': [123.429096, 41.796767],
    '安徽': [117.283042, 31.86119],
    '黑龙江': [126.642464, 45.756967],
    '广西': [108.320004, 22.82402],
    '陕西': [108.948024, 34.263161],
    '山西': [112.549248, 37.857014],
    '新疆': [87.617733, 43.792818],
    '吉林': [125.3245, 43.886841],
    '云南': [102.712251, 25.040609],
    '贵州': [106.713478, 26.578343],
    '甘肃': [103.823557, 36.058039],
    '内蒙古': [111.670801, 40.818311],
    '江西': [115.892151, 28.676493],
    '福建': [119.306239, 26.075302],
    '海南': [110.33119, 20.031971],
    '宁夏': [106.278179, 38.46637],
    '青海': [101.778916, 36.623178],
    '西藏': [91.132212, 29.660361]
  };
  return geoCoordMap[name];
};
</script>

<style lang="less" scoped>
.data-board-split {
  width: 100%;
  padding: 20px;
  background-color: #f5f7fa;
  height: 90vh;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      font-size: 24px;
      color: #333;
      margin: 0;
    }

    .time-selector {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .data-tabs {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
    height:100%;

    :deep(.el-tabs__header) {
      margin-bottom: 20px;
    }

    :deep(.el-tabs__item) {
      font-size: 16px;
      padding: 0 20px;
    }

    .chart-container {
      height: 700px;
      width: 100%;

      .chart {
        height: 100%;
        width: 100%;
      }

      .map-chart {
        height: 100%;
      }
    }
  }
}
</style>
